package com.jxmobi.car.core.service;

import com.jxmobi.base.util.Objects2;
import com.jxmobi.car.core.model.CarModel;
import com.jxmobi.car.core.repository.CarModelRepository;
import com.jxmobi.car.core.vo.CarNewVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * @author fei <a href="mailto:xchen@jxmobi.com">Email the author</a>
 * @version 1.0 7/28/16
 */
@Service
@Transactional
public class CarService {
    private static final Logger log = LoggerFactory.getLogger(CarService.class);

    @Autowired private CarModelRepository carRepository;

    public CarModel findByModel(String model) {
        return this.carRepository.findByModel(model);
    }

    public CarModel saveNewCar(CarNewVo newCar) {

        CarModel carModel = new CarModel();
        carModel.setBrand(newCar.getBrand());

        // check the db of the existence of the model
        CarModel persistCar = this.carRepository.findByModel(newCar.getModel());
        Objects2.requireNull(persistCar, "model already existed");

        carModel.setModel(newCar.getModel());
        carModel.setCardNo(newCar.getCarNo());

        return this.carRepository.save(carModel);
    }

    public Page<CarModel> findCarsByPage(Pageable pageable) {
        return this.carRepository.findAll(pageable);
    }
}
